from machine import Pin, ADC
import time
from time import sleep
# import ulogger


INFRARED_PIN_NUM = 8
INFRARED_ACTIVATE_DELAY_OFF = 3

RADAR_PIN_NUM = 9

BRIGHTNESS_PIN_NUM = 4
LED_ON_BRIGHTNESS_THRESHOLD = 35
LED_OFF_BRIGHTNESS_THRESHOLD = 70

LED_MOS_PIN_NUM = 12


def read_brightness(pin):
    raw_value = pin.read_u16()
    mapped_value = int((raw_value / 65535) * 100)
    return mapped_value

def light_on_routine(brightness_pin: ADC, radar_pin: Pin, led_mos_pin: Pin):
    print('\n  Light on routine >>>>>')
    led_mos_pin.value(1)
    time.sleep(INFRARED_ACTIVATE_DELAY_OFF) # 至少睡够3秒钟，等红外探头恢复到未激活状态

    while True: 
        brightness = read_brightness(brightness_pin)
        if read_brightness(brightness_pin) >= LED_OFF_BRIGHTNESS_THRESHOLD:
            print(f"  Current brightness ({brightness}) is too high")
            break

        if radar_pin.value() == 0:
            print(f"  Radar signal lost")
            break

        sleep(0.1)

    led_mos_pin.value(0)
    print('  Light on routine <<<<<\n')

def main():
    try:
        # logger = ulogger.Logger(__name__)

        # logger.info("Welcome to RT-Thread MicroPython!")

        infrared_pin = Pin(INFRARED_PIN_NUM, Pin.IN, Pin.PULL_DOWN)
        brightness_pin = ADC(Pin(BRIGHTNESS_PIN_NUM))
        radar_pin = Pin(RADAR_PIN_NUM, Pin.IN, Pin.PULL_DOWN)

        led_mos_pin = Pin(LED_MOS_PIN_NUM, Pin.OUT, value = 0)

        while True:
            if infrared_pin.value() == 1:
                print(f"Infrared detected!")

                brightness = read_brightness(brightness_pin)
                if brightness <= LED_ON_BRIGHTNESS_THRESHOLD:
                    print(f'  Current brightness ({brightness}) is low enough')
                    light_on_routine(brightness_pin, radar_pin, led_mos_pin)
                else:
                    print(f'  Current brightness ({brightness}) is too high, no need to light on')
                    print(f'  Waiting for infrared cool down...')
                    while infrared_pin.value() == 1: 
                        sleep(0.1)
                    print(f'  Infrared cooled down')
            else:
                sleep(0.1)
    except KeyboardInterrupt:
        led_mos_pin.value(0)
    
if __name__ == '__main__':
    main()